<!DOCTYPE html>
<html
  lang="zh"
  xmlns:th="http://www.thymeleaf.org"
  xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
  <head>
    <th:block th:include="include :: header('绘声绘影管理')" />
    <th:block th:include="include :: layout-latest-css" />
    <style>
      body {
        background: #f5f7fa;
      }
      .content-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
      }
      .search-panel {
        background: white;
        border-radius: 12px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
      .toolbar-section {
        background: white;
        border-radius: 12px;
        padding: 16px 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      /* 卡片流布局 */
      #dynamicList {
        display: flex;
        flex-direction: column;
        gap: 20px;
      }

      .dynamic-card {
        background: white;
        border-radius: 16px;
        padding: 24px;
        box-shadow: 0 2px 16px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
        border: 1px solid #f0f0f0;
        position: relative;
        cursor: pointer;
      }
      .dynamic-card:hover {
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
        transform: translateY(-2px);
      }

      .dynamic-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;
      }

      .dynamic-title {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 8px;
        color: #333;
        line-height: 1.4;
        flex: 1;
        padding-right: 10px;
      }

      .dynamic-meta {
        display: flex;
        gap: 20px;
        margin-bottom: 16px;
        font-size: 14px;
        color: #666;
      }

      .meta-item {
        display: flex;
        align-items: center;
        gap: 5px;
      }

      .dynamic-content {
        color: #555;
        line-height: 1.6;
        margin-bottom: 16px;
        font-size: 14px;
      }

      .dynamic-image {
        width: 100%;
        max-height: 200px;
        object-fit: cover;
        border-radius: 8px;
        margin-bottom: 16px;
      }

      .dynamic-stats {
        display: flex;
        gap: 20px;
        margin-bottom: 16px;
        font-size: 14px;
        color: #666;
      }

      .stat-item {
        display: flex;
        align-items: center;
        gap: 5px;
      }

      .dynamic-actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
      }

      .status-badge {
        position: absolute;
        top: 20px;
        right: 20px;
        padding: 4px 12px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
      }

      .status-pending {
        background: #fff3cd;
        color: #856404;
      }

      .status-approved {
        background: #d4edda;
        color: #155724;
      }

      .status-rejected {
        background: #f8d7da;
        color: #721c24;
      }

      .btn-card {
        padding: 6px 12px;
        border-radius: 6px;
        border: none;
        font-size: 12px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 4px;
      }

      .btn-primary-card {
        background: #007bff;
        color: white;
      }
      .btn-primary-card:hover {
        background: #0056b3;
        color: white;
      }

      .btn-success-card {
        background: #28a745;
        color: white;
      }
      .btn-success-card:hover {
        background: #1e7e34;
        color: white;
      }

      .btn-warning-card {
        background: #ffc107;
        color: #212529;
      }
      .btn-warning-card:hover {
        background: #e0a800;
      }

      .btn-danger-card {
        background: #dc3545;
        color: white;
      }
      .btn-danger-card:hover {
        background: #c82333;
        color: white;
      }

      .btn-info-card {
        background: #17a2b8;
        color: white;
      }
      .btn-info-card:hover {
        background: #138496;
        color: white;
      }

      .select-list ul {
        list-style: none;
        margin: 0;
        padding: 0;
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        align-items: center;
      }

      .select-list li {
        display: flex;
        align-items: center;
        gap: 8px;
        white-space: nowrap;
      }

      .select-list li label {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin: 0;
        flex-shrink: 0;
      }

      .form-control-custom {
        padding: 8px 12px;
        border: 1px solid #e0e0e0;
        border-radius: 20px;
        font-size: 14px;
        height: 38px;
        width: 160px;
        box-sizing: border-box;
        background: #ffffff;
        transition: border-color 0.2s ease, box-shadow 0.2s ease;
        outline: none;
      }

      .form-control-custom:focus {
        border-color: #20c997;
        box-shadow: 0 0 0 2px rgba(32, 201, 151, 0.1);
      }

      .form-control-custom::placeholder {
        color: #999;
        font-size: 14px;
      }

      .toolbar-left {
        display: flex;
        gap: 8px;
      }

      .toolbar-right {
        color: #666;
        font-size: 14px;
      }

      .no-data {
        text-align: center;
        padding: 60px 20px;
        color: #999;
        font-size: 16px;
      }

      .pagination-wrapper {
        display: flex;
        justify-content: center;
        margin-top: 30px;
      }

      /* 详情页面样式 */
      .detail-container {
        display: none;
        background: white;
        border-radius: 16px;
        padding: 30px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
      }

      .detail-container.active {
        display: block;
      }

      .detail-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 30px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f0f0f0;
      }

      .detail-title {
        font-size: 24px;
        font-weight: 600;
        color: #333;
      }

      .back-btn {
        background: #6c757d;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
      }

      .back-btn:hover {
        background: #5a6268;
      }

      .detail-content {
        font-size: 16px;
        line-height: 1.8;
        color: #555;
        margin: 20px 0;
      }

      .detail-meta {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
        margin: 20px 0;
        padding: 20px;
        background: #f8f9fa;
        border-radius: 8px;
      }

      .detail-meta-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
      }

      .detail-meta-item .label {
        font-weight: 600;
        color: #666;
      }

      .detail-meta-item .value {
        color: #333;
      }

      .detail-image {
        max-width: 100%;
        height: auto;
        border-radius: 8px;
        margin: 20px 0;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      @media (max-width: 768px) {
        .dynamic-header {
          flex-direction: column;
          align-items: flex-start;
        }

        .dynamic-meta {
          flex-wrap: wrap;
        }

        .dynamic-actions {
          justify-content: flex-start;
        }

        .search-form {
          flex-direction: column;
          align-items: stretch;
        }

        .form-group {
          min-width: unset;
        }

        .search-buttons {
          align-self: flex-start;
          margin-top: 16px;
        }

        .toolbar-section {
          flex-direction: column;
          gap: 16px;
          align-items: stretch;
        }
      }
    </style>
  </head>
  <body>
    <div class="content-container">
      <!-- 搜索面板 -->
      <div class="search-panel">
        <form id="formId">
          <div class="select-list">
            <ul>
              <li>
                <label>标题：</label>
                <input
                  type="text"
                  name="title"
                  class="form-control-custom"
                  placeholder="请输入标题"
                />
              </li>
              <li>
                <label>发布者：</label>
                <input
                  type="text"
                  name="publisher"
                  class="form-control-custom"
                  placeholder="请输入发布者"
                />
              </li>
              <li>
                <label>审核状态：</label>
                <select name="auditFlag" class="form-control-custom">
                  <option value="" selected>所有</option>
                  <option value="0">待审核</option>
                  <option value="1">已通过</option>
                  <option value="2">已拒绝</option>
                </select>
              </li>
              <li>
                <a
                  class="btn btn-primary btn-rounded btn-sm"
                  onclick="searchDynamics()"
                  ><i class="fa fa-search"></i>&nbsp;搜索</a
                >
                <a
                  class="btn btn-warning btn-rounded btn-sm"
                  onclick="resetSearch()"
                  ><i class="fa fa-refresh"></i>&nbsp;重置</a
                >
              </li>
            </ul>
          </div>
        </form>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar-section">
        <div class="toolbar-left">共 <span id="totalCount">0</span> 条动态</div>
        <div class="toolbar-right">
          <button
            class="btn btn-success"
            onclick="addDynamic()"
            shiro:hasPermission="hui:interact:graphic:add"
          >
            <i class="fa fa-plus"></i> 新增动态
          </button>
        </div>
      </div>

      <!-- 详情页面 -->
      <div id="detailContainer" class="detail-container">
        <div class="detail-header">
          <div class="detail-title" id="detailTitle">动态详情</div>
          <button class="back-btn" onclick="backToList()">
            <i class="fa fa-arrow-left"></i> 返回列表
          </button>
        </div>
        <div class="detail-meta" id="detailMeta">
          <!-- 详情元信息 -->
        </div>
        <div class="detail-content" id="detailContent">
          <!-- 详情内容 -->
        </div>
        <div id="detailImage">
          <!-- 详情图片 -->
        </div>
      </div>

      <!-- 动态列表 -->
      <div id="listContainer">
        <div id="dynamicList">
          <!-- 动态卡片将通过JavaScript动态生成 -->
        </div>

        <!-- 暂无数据 -->
        <div id="noData" class="no-data" style="display: none">
          <i
            class="fa fa-inbox"
            style="font-size: 48px; margin-bottom: 16px; color: #ddd"
          ></i>
          <div>暂无动态数据</div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <div id="pagination"></div>
        </div>
      </div>
    </div>

    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
      var prefix = ctx + "hui/interact/graphic";

      var currentPage = 1;
      var pageSize = 10;
      var total = 0;

      $(function () {
        // 将loadDynamics函数暴露到全局，供子页面调用
        window.loadDynamics = loadDynamics;

        // 也暴露到其他可能的位置
        if (window.parent && window.parent !== window) {
          window.parent.loadDynamics = loadDynamics;
        }

        if (window.top && window.top !== window) {
          window.top.loadDynamics = loadDynamics;
        }

        loadDynamics();
      });

      // 加载动态列表
      function loadDynamics() {
        var formData = $("#formId").serialize();

        $.ajax({
          url: prefix + "/list",
          type: "POST",
          data: formData + "&pageNum=" + currentPage + "&pageSize=" + pageSize,
          success: function (result) {
            console.log("数据加载结果:", result);
            if (result.code === 0) {
              console.log(
                "原始数据条数:",
                result.rows ? result.rows.length : 0
              );
              renderDynamics(result.rows);
              total = result.total;
              $("#totalCount").text(total);
              renderPagination();
            } else {
              $.modal.msgError(result.msg);
            }
          },
          error: function () {
            $.modal.msgError("加载失败，请重试");
          },
        });
      }

      // 渲染动态卡片
      function renderDynamics(dynamics) {
        var html = "";
        var visibleCount = 0;

        console.log("开始渲染动态，数据:", dynamics);

        if (dynamics && dynamics.length > 0) {
          dynamics.forEach(function (item, index) {
            html += generateDynamicCard(item);
            visibleCount++;
          });
          $("#dynamicList").html(html);
          if (html === "") {
            $("#noData").show();
          } else {
            $("#noData").hide();
          }
        } else {
          $("#dynamicList").html("");
          $("#noData").show();
        }

        // 更新可见的动态数量显示
        updateVisibleCount(visibleCount);
      }

      // 更新可见动态数量
      function updateVisibleCount(visibleCount) {
        if (visibleCount !== total) {
          $("#totalCount").text(visibleCount + " (共" + total + "条)");
        } else {
          $("#totalCount").text(total);
        }
      }

      // 生成动态卡片HTML
      function generateDynamicCard(item) {
        var statusClass = "";
        var statusText = "";

        switch (item.auditFlag) {
          case "0":
            statusClass = "status-pending";
            statusText = "待审核";
            break;
          case "1":
            statusClass = "status-approved";
            statusText = "已通过";
            break;
          case "2":
            statusClass = "status-rejected";
            statusText = "已拒绝";
            break;
          default:
            statusClass = "status-pending";
            statusText = "待审核";
        }

        var content = item.content || "";
        var shortContent =
          content.length > 200 ? content.substring(0, 200) + "..." : content;

        // 移除HTML标签
        shortContent = shortContent.replace(/<[^>]*>/g, "");

        var actionsHtml = "";

        // 详情按钮
        actionsHtml +=
          '<a href="javascript:void(0)" class="btn-card btn-info-card" onclick="viewDetail(' +
          item.id +
          ')">';
        actionsHtml += '<i class="fa fa-eye"></i> 详情</a>';

        // 编辑按钮
        actionsHtml +=
          '<a href="javascript:void(0)" class="btn-card btn-warning-card" onclick="editDynamic(' +
          item.id +
          ')">';
        actionsHtml += '<i class="fa fa-edit"></i> 编辑</a>';

        // 评论管理按钮
        actionsHtml +=
          '<a href="javascript:void(0)" class="btn-card btn-primary-card" onclick="viewComments(' +
          item.id +
          ')">';
        actionsHtml += '<i class="fa fa-comment"></i> 评论管理</a>';

        // 审核通过按钮
        if (item.auditFlag == "0") {
          actionsHtml +=
            '<a href="javascript:void(0)" class="btn-card btn-success-card" onclick="auditDynamic(' +
            item.id +
            ', 1)">';
          actionsHtml += '<i class="fa fa-check"></i> 通过</a>';
        }

        // 审核拒绝按钮
        if (item.auditFlag == "0") {
          actionsHtml +=
            '<a href="javascript:void(0)" class="btn-card btn-warning-card" onclick="auditDynamic(' +
            item.id +
            ', 2)">';
          actionsHtml += '<i class="fa fa-times"></i> 拒绝</a>';
        }

        // 删除按钮
        actionsHtml +=
          '<a href="javascript:void(0)" class="btn-card btn-danger-card" onclick="deleteDynamic(' +
          item.id +
          ')">';
        actionsHtml += '<i class="fa fa-trash"></i> 删除</a>';

        return `
          <div class="dynamic-card">
            <div class="status-badge ${statusClass}">${statusText}</div>

            <div class="dynamic-header">
              <div class="dynamic-title">${item.title || "无标题"}</div>
            </div>


            <div class="dynamic-meta">
              <div class="meta-item">
                ${
                  item.avatar
                    ? `<img src="${item.avatar}" alt="头像" style="width: 24px; height: 24px; border-radius: 50%; margin-right: 5px;">`
                    : '<i class="fa fa-user"></i>'
                }
                <span>${item.publisher || "匿名"}</span>
              </div>
              <div class="meta-item">
                <i class="fa fa-clock-o"></i>
                <span>${item.createTime || ""}</span>
              </div>
            </div>

            <div class="dynamic-content">${shortContent}</div>

            <div class="dynamic-stats">
              <div class="stat-item">
                <i class="fa fa-eye"></i>
                <span>${item.viewCount || 0}</span>
              </div>
              <div class="stat-item">
                <i class="fa fa-heart"></i>
                <span>${item.likeCount || 0}</span>
              </div>
            </div>

            <div class="dynamic-actions">
              ${actionsHtml}
            </div>
          </div>
        `;
      }

      // 搜索动态
      function searchDynamics() {
        currentPage = 1;
        loadDynamics();
      }

      // 重置搜索
      function resetSearch() {
        $("#formId")[0].reset();
        currentPage = 1;
        loadDynamics();
      }

      // 新增动态
      function addDynamic() {
        var url = prefix + "/add";
        $.modal.open("新增动态", url, "900", "600");
      }

      // 编辑动态
      function editDynamic(id) {
        var url = prefix + "/edit/" + id;
        $.modal.open("编辑动态", url, "900", "600");
      }

      // 查看详情
      function viewDetail(id) {
        // 直接跳转到详情页
        window.location.href = prefix + "/detail/" + id;
      }

      // 显示详情页面
      function showDetailPage(data) {
        // 填充详情内容
        $("#detailTitle").text(data.title || "无标题");

        // 元信息
        var metaHtml = `
          <div class="detail-meta-item">
            <span class="label">发布者：</span>
            <span class="value">
              ${
                data.avatar
                  ? `<img src="${data.avatar}" alt="头像" style="width: 20px; height: 20px; border-radius: 50%; margin-right: 5px; vertical-align: middle;">`
                  : ""
              }
              ${data.publisher || "匿名"}
            </span>
          </div>
          <div class="detail-meta-item">
            <span class="label">发布时间：</span>
            <span class="value">${data.createTime || ""}</span>
          </div>
          <div class="detail-meta-item">
            <span class="label">浏览量：</span>
            <span class="value">${data.viewCount || 0}</span>
          </div>
          <div class="detail-meta-item">
            <span class="label">点赞数：</span>
            <span class="value">${data.likeCount || 0}</span>
          </div>
          <div class="detail-meta-item">
            <span class="label">审核状态：</span>
            <span class="value">${getAuditStatusText(data.auditFlag)}</span>
          </div>
        `;
        $("#detailMeta").html(metaHtml);

        // 内容
        $("#detailContent").html(data.content || "无内容");

        // 图片
        if (data.imageUrl) {
          $("#detailImage").html(
            `<img src="${data.imageUrl}" alt="动态图片" class="detail-image">`
          );
        } else {
          $("#detailImage").html("");
        }

        // 显示详情页，隐藏列表页
        $("#listContainer").hide();
        $("#detailContainer").addClass("active");
      }

      // 返回列表
      function backToList() {
        $("#detailContainer").removeClass("active");
        $("#listContainer").show();
      }

      // 获取审核状态文本
      function getAuditStatusText(auditFlag) {
        switch (auditFlag) {
          case "0":
            return "待审核";
          case "1":
            return "已通过";
          case "2":
            return "已拒绝";
          default:
            return "待审核";
        }
      }

      // 查看评论
      function viewComments(id) {
        var url = prefix + "/comments/" + id;
        $.modal.open("评论管理", url, "800", "600");
      }

      // 审核动态
      function auditDynamic(id, flag) {
        var msg =
          flag == 1
            ? "确定要通过此动态的审核吗？"
            : "确定要拒绝此动态的审核吗？";
        $.modal.confirm(msg, function () {
          $.ajax({
            url: prefix + "/audit",
            type: "POST",
            data: { id: id, auditFlag: flag },
            success: function (result) {
              if (result.code === 0) {
                // 检查当前是否有审核状态筛选
                var currentAuditFlag = $('select[name="auditFlag"]').val();
                var statusText = flag == 1 ? "已通过" : "已拒绝";

                // 如果当前筛选条件会导致审核后的数据不显示，给出提示
                if (currentAuditFlag && currentAuditFlag != flag.toString()) {
                  $.modal.msgSuccess(
                    "审核成功！该动态状态已变更为" +
                      statusText +
                      "，如需查看请调整筛选条件。"
                  );
                  // 自动重置筛选条件显示所有数据
                  $('select[name="auditFlag"]').val("");
                } else {
                  $.modal.msgSuccess("操作成功");
                }

                loadDynamics();
              } else {
                $.modal.msgError(result.msg);
              }
            },
          });
        });
      }

      // 删除动态
      function deleteDynamic(id) {
        $.modal.confirm("确定要删除此动态吗？", function () {
          $.ajax({
            url: prefix + "/remove",
            type: "POST",
            data: { ids: id },
            success: function (result) {
              if (result.code === 0) {
                $.modal.msgSuccess("删除成功");
                loadDynamics();
              } else {
                $.modal.msgError(result.msg);
              }
            },
          });
        });
      }

      // 渲染分页
      function renderPagination() {
        if (total <= pageSize) {
          $("#pagination").html("");
          return;
        }

        var totalPages = Math.ceil(total / pageSize);
        var html = '<ul class="pagination">';

        // 上一页
        if (currentPage > 1) {
          html +=
            '<li><a href="javascript:void(0)" onclick="changePage(' +
            (currentPage - 1) +
            ')">上一页</a></li>';
        }

        // 页码
        var start = Math.max(1, currentPage - 2);
        var end = Math.min(totalPages, currentPage + 2);

        for (var i = start; i <= end; i++) {
          if (i === currentPage) {
            html +=
              '<li class="active"><a href="javascript:void(0)">' +
              i +
              "</a></li>";
          } else {
            html +=
              '<li><a href="javascript:void(0)" onclick="changePage(' +
              i +
              ')">' +
              i +
              "</a></li>";
          }
        }

        // 下一页
        if (currentPage < totalPages) {
          html +=
            '<li><a href="javascript:void(0)" onclick="changePage(' +
            (currentPage + 1) +
            ')">下一页</a></li>';
        }

        html += "</ul>";
        $("#pagination").html(html);
      }

      // 切换页码
      function changePage(page) {
        currentPage = page;
        loadDynamics();
      }
    </script>
  </body>
</html>
